package com.library.hibernatejpa.dao;

import java.util.Collection;
import java.util.List;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.library.hibernatejpa.entity.Author;
import com.library.hibernatejpa.entity.Publisher;
import com.library.hibernatejpa.entity.Book;

/**
 * Implementation of LibraryDAO implemented by extending Spring's HibernateDaoSupport 
 * 
 */
public class LibraryDAOHibernateImpl extends HibernateDaoSupport implements LibraryDAO
{
  public Collection<Author> getAuthors()
  {
    return getHibernateTemplate().loadAll(Author.class);
  }

  public Author getAuthorById(Integer id)
  {
    Author author = (Author) getHibernateTemplate().load(Author.class, id); 
    System.out.println("Got author: "+author);
    return author;
  }

  public Author saveAuthor(Author author)
  {
    getHibernateTemplate().saveOrUpdate(author);
    return author;
  }

  public Publisher getPublisherById(Integer id)
  {
    Publisher publisher = (Publisher) getHibernateTemplate().load(Publisher.class, id); 
    System.out.println("Got publisher: "+publisher);
    return publisher;
  }

  public Publisher savePublisher(Publisher publisher)
  {
    getHibernateTemplate().saveOrUpdate(publisher);
    return publisher;
  } 
  
  public Book saveBook(Book book)
  {
    getHibernateTemplate().saveOrUpdate(book);
    return book;
  } 
  
  public Book getBookById(Integer id)
  {
    Book book = (Book) getHibernateTemplate().load(Book.class, id); 
    System.out.println("Got book: "+book);
    return book; 
  }
  
  public List<Publisher> searchPublishersByTitle(String name)
  {
    return getHibernateTemplate().findByNamedQuery("publisher.nameLike", "%"+name+"%");
  }

  public List<Book> searchBooksByPublisher(Integer id)
  {
    return getHibernateTemplate().findByNamedQuery("publisher.getPublisherBooks", id);
  }

}